package org.jeecg.config.feign;

import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class FeignConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 拿到当前请求Request
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != requestAttributes) {
            HttpServletRequest request = requestAttributes.getRequest();
            String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
            String type = request.getHeader(CommonConstant.FEIGN_AUTH_TYPE);
            if (StrUtil.isEmpty(type)) {
                type = CommonConstant.FEIGN_AUTH_N;
            }

            if (token != null) {
                requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, token);
                requestTemplate.header(CommonConstant.FEIGN_REQUEST, type);
            }
        } else {
            requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, CommonConstant.FEIGN_AUTH_TYPE);
            requestTemplate.header(CommonConstant.FEIGN_REQUEST, CommonConstant.FEIGN_AUTH_N);
        }
    }


}
